﻿using System.Data;
using MySql.Data.MySqlClient;

namespace VfAccountApps.WebForm
{
    /// <summary>
    ///
    /// </summary>
    internal class DatabaseHelper
    {
        private static MySqlConnection con;

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static bool connection()
        {
            bool flag = true;
            con = new MySqlConnection();
            con.ConnectionString = "server=localhost; database = vfa; user id = root; password= ";
            try
            {
                con.Open();
            }
            catch (MySqlException ex)
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static DataTable select(string query)
        {
            DataTable dt = new DataTable();

            if (connection())
            {
                MySqlDataAdapter a = new MySqlDataAdapter(query, con);

                try
                {
                    a.Fill(dt);
                }
                catch (MySqlException ex)
                {
                    //MessageBox.Show(ex.Message);
                }
            }

            disconnect();

            return dt;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="query"></param>
        public static int insert(string query)
        {
            MySqlCommand cmd = new MySqlCommand(query);

            if (connection())
            {
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;

                try
                {
                    cmd.ExecuteNonQuery();
                    //MessageBox.Show("Successfully Inserted!!!");
                }
                catch (MySqlException ex)
                {
                    //MessageBox.Show(ex.Message);
                }
                finally
                {
                    cmd.Dispose();
                }
            }

            disconnect();

            return (int)cmd.LastInsertedId;
        }

        /// <summary>
        ///
        /// </summary>
        public static void disconnect()
        {
            try
            {
                con.Close();
                con.Dispose();
            }
            catch (MySqlException ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        public static MySqlDataAdapter selectAdapter(string query)
        {
            connection();

            DataTable dt = new DataTable();

            MySqlDataAdapter a = new MySqlDataAdapter(query, con);

            return a;
        }
    }
}